package com.zwxu;

import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.plugins.ActionPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.ScriptPlugin;
import org.elasticsearch.script.AbstractDoubleSearchScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.NativeScriptFactory;
import java.util.Collections;
import java.util.List;
import java.util.Map;

//https://blog.csdn.net/makefriend7/article/details/60770564
public class MyFirstPlugin extends Plugin implements ActionPlugin, ScriptPlugin {

    public MyFirstPlugin() {
        super();
    }


    public List<NativeScriptFactory> getNativeScripts() {
        return Collections.singletonList(new MyNativeScriptFactory());
    }

    public static class MyNativeScriptFactory implements NativeScriptFactory {
        public ExecutableScript newScript(@Nullable Map<String, Object> params) {
            String featureStr = params == null ? null : XContentMapValues.nodeStringValue(params.get("feature"), null);
            if (featureStr == null) {
                System.out.println("Missing the field parameter ");
            }
            return new MyScript(featureStr);
        }

        public boolean needsScores() {
            return false;
        }

        public String getName() {
            return "my_native_script";
        }
    }

    public static class MyScript extends AbstractDoubleSearchScript {
        private final String featureStr;

        public MyScript(String featureStr) {
            this.featureStr = featureStr;
        }

        @Override
        public double runAsDouble() {
            String strSrcFeature = (String) source().get("feature");
            int nLen1 = featureStr.length();
            int nLen2 = strSrcFeature.length();
            if (nLen1 == nLen2) {
                return 99.9;
            }
            if (nLen1 < nLen2) {
                return 66.6;
            } else {
                return 33.3;
            }
        }
    }
}
